package com.jvyou.app.ds.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jvyou.app.common.domain.dto.RoleDto;
import com.jvyou.app.common.domain.entity.Role;
import com.jvyou.app.common.domain.model.PageResult;
import com.jvyou.app.common.utils.orm.WrapperTool;
import com.jvyou.app.ds.mapper.RoleMapper;
import com.jvyou.app.ds.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * 角色信息表(Role)表服务实现类
 *
 * @author 橘柚
 * @since 2025-03-05 14:11:41
 */
@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {


    @Autowired
    private RoleMapper roleMapper;

    private QueryWrapper<Role> getWrapper(RoleDto roleDto) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        WrapperTool.notEmptyEq(queryWrapper, "name", roleDto.getName());
        WrapperTool.notEmptyEq(queryWrapper, "role_key", roleDto.getRoleKey());
        WrapperTool.notEmptyEq(queryWrapper, "status", roleDto.getStatus());
        return queryWrapper;
    }

    @Override
    public PageResult<Role> pageRole(RoleDto roleDto) {
        IPage<Role> page = new Page<>(roleDto.getCurrent(), roleDto.getPageSize());
        page = page(page, getWrapper(roleDto));
        return PageResult.success(page.getTotal(), page.getRecords());
    }

    @Override
    public List<Role> listRole(RoleDto roleDto) {
        return list(getWrapper(roleDto));
    }

    @Transactional
    @Override
    public Boolean assignPermissions(Long id, List<Long> menuIds) {
        // 1. 先删除原来存在的菜单信息
        roleMapper.deleteRoleMenuByRoleId(id);
        if (menuIds.isEmpty()) {
            return true;
        }
        // 2. 添加新的菜单信息
        roleMapper.insertRoleMenu(id, menuIds);
        return true;
    }
}
